<template>
  <div class="addMission">
    <div class="backFont"><el-button icon="el-icon-arrow-left" @click="back()">返回</el-button></div>
    <el-form
      :model="addForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm errorForm mt20"
    >
      <el-form-item class="noRequire" label="*农事类型：" prop="code">
        <div class="greyColor" v-if="$route.query.code">{{ addForm.name }}</div>
        <!-- <el-select v-model="addForm.code"  placeholder="请选择农事类型">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select> -->
        <div v-else>
          <el-button
            :disabled="addForm.id ? true : false"
            :class="addForm.code == item.code && 'checkBoxAll'"
            @click="addSelect(item.code)"
            v-for="item in options" :key="item.id"
          >
            {{ item.name }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item class="noRequire" label="*地块：">
        <!-- <el-input v-model="landDetail.landName" :disabled="true"> </el-input> -->
        <!-- <el-button class="checkLand" round>
          {{ landDetail.landDetail }}
        </el-button> -->
        <!-- <div class="greyColor">{{ landDetail.landName }}</div> -->
        <el-select class="widthInput" v-model="landDetail.landId" placeholder="请选择">
          <el-option
            v-for="item in landinfoList"
            :key="item.landId"
            :label="item.landName"
            :value="item.landId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="noRequire" label="*农资：" v-if="NsCode(addForm.code)">
        <div class="farmStockListBox">
          <div
            class="farmStockList"
            v-for="(item, index) in addForm.agriList"
            :key="item.id"
          >
            <!-- <div class="icon">
              <img src="../../assets/img/huafeiicon.png" alt="" />
            </div> -->
            <div class="content">
              <div class="farmStockName">
                <span>{{ item.name}}</span>
                <div class="landType">{{  addForm.id ? item.type : item.typeFormat }}</div>
              </div>
              <div class="manufacturer">
                规格：{{ item.specifications }}
              </div>
              <div class="manufacturer">
                <div>
                  {{ item.manufacturer }}
                </div>
                <div class="blackColor">
                  库存量：{{ item.remainingQuantity }} 公斤
                </div>
              </div>
            </div>
            <!-- 校验数组 -->
            <div class="num">
              <el-form-item
                :prop="`agriList.${index}.num`"
                :rules="rules.agriList.num"
              >
                <!-- <el-form-item prop="agriList"> -->
                <!-- <el-input style="width:10px;" class="inp" v-model="item.num" /> -->
                <el-input type="number" :readonly="addForm.id" placeholder="请输入使用数量" v-model="item.num" @input="item.num > Number(item.remainingQuantity) ? item.num = item.remainingQuantity : ''" :min="0" :max="item.remainingQuantity">
                  <!-- <template slot="append">公斤</template> -->
                </el-input>
                公斤
              </el-form-item>
            </div>
            <div v-if="!addForm.id" class="del" @click="del(index)">
              <i class="el-icon-error"></i>
            </div>
          </div>
        </div>
        <div class="agriListAdd">
          <el-button
            type="primary"
            @click="dialogVisible = !dialogVisible"
            v-if="!addForm.id"
          >
            {{addForm.agriList.length ? '继续添加' : '添加农资'}}
          </el-button>
          <span>Tips：使用数量大于0小于等于库存量</span>
        </div>
      </el-form-item>
      <el-form-item class="noRequire"  label="*作业方式：" prop="way">
        <!-- <el-radio-group v-model="addForm.way">
          <el-radio :label="'0'">人工</el-radio>
          <el-radio :label="'1'">机械</el-radio>
        </el-radio-group> -->
        <el-button
          class="typeBtn"
          :class="addForm.way == 0 && 'checkBoxAll'"
          @click="addForm.way = 0"
        >
          人工
        </el-button>
        <el-button
          class="typeBtn"
          :class="addForm.way == 1 && 'checkBoxAll'"
          @click="addForm.way = 1"
        >
          机械
        </el-button>
      </el-form-item>
      <el-form-item class="noRequire" label="*操作时间：" prop="time">
        <el-date-picker
          class="widthInput"
          v-model="addForm.time"
          type="date"
          placeholder="选择日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item class="noRequire" label="*操作人：" prop="participantsId">
        <el-select class="widthInput" v-model="addForm.participantsId" placeholder="请选择">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="农事照片">
        <upload
          ref="upload"
          v-model="addForm.picture"
          :isShowTip="false"
          :limit="3">
        </upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          type="textarea"
          placeholder="请输入备注内容"
          v-model="addForm.remark"
          style="width: 700px"
          :rows="4"
          maxlength="100"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >{{ missionDetail && missionDetail.id ? '修改农事' : '立即创建'}}</el-button
        >
        <el-button v-if="!addForm.id" @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item> -->
    </el-form>
    <div class="submitBottom">
      <el-button
        size="small"
        class="editBtn editBtnNone"
        @click="back()"
        >取消</el-button
      >
      <el-button
        class="editBtn"
        type="primary"
        size="small"
        @click="submitForm('ruleForm')"
      >
        确定
      </el-button>
    </div>
    <!-- 农资弹窗 -->
    <el-dialog
      title="选择农资"
      :show-close="false"
      :visible.sync="dialogVisible"
      width="1100px"
      :before-close="handleClose"
    >
      <div class="dialogSearch" slot="title">
        <div class="searchFlex">
          <span class="searchType">选择农资</span>
          <el-select size="small"  @input="farmStockSearch()" v-model="keywordType" class="select"  clearable placeholder="请选择农资类型">
            <el-option
              v-for="item in NZZLlist"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </div>
        <div class="searchFlex">
          <el-input
            size="small"
            class="searchInp"
            @input="farmStockSearch()"
            suffix-icon="el-icon-search"
            v-model="keyword"
            placeholder="搜索农资"
          ></el-input>
          <i class="el-icon-close" @click="handleClose()"></i>
        </div>
      </div>
      <farmStockDialog
        ref="farmStockDialog"
        :farmStockList="farmStockList"
        :total="total"
        @addFarmStock="addFarmStock"
        :farmStockAddList="farmStockAddList"
      ></farmStockDialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  delpictureApi,
  addArgiMissionApi,
  getUserListApi,
  getFarmsStockInventoryApi,
  updateArgiMissionApi
} from '@/api/mission'
import { getSysSonDictListApi } from '@/api/dict'
import upload from './components/upload.vue'
import farmStockDialog from './components/farmStockDialog'
import { getLandinfoListApi } from '@/api/baseInfo'
export default {
  name: 'SevencolorUserIndex',
  components: {
    upload, // 上传组件
    farmStockDialog
  },

  data () {
    return {
      keyword: '',
      keywordType: '',
      addForm: {
        baseId: '',
        code: '', // 农事编码
        landId: 1,
        participants: '', // 操作人
        participantsId: '', // 操作人Id
        time: '',
        way: 0, // 操作方式
        picture: '',
        remark: '',
        agriList: []
      },
      params: {
        current: 1,
        pageSize: 6
      },
      total: null,
      baseId: 1,
      addMissionData: {},
      rules: {
        code: [{ required: true, message: '请选择农事类型', trigger: 'blur' }],
        way: [{ required: true, message: '请选作业方式', trigger: 'blur' }],
        time: [{ required: true, message: '请选择农事时间', trigger: 'blur' }],
        participantsId: [
          { required: true, message: '请选择操作人', trigger: 'blur' }
        ],
        agriList: {
          num: [{ required: true, message: '请输入农资数量', trigger: 'blur' }]
        }
      },
      options: [],
      userList: [], // 用户字典0
      dialogVisible: false, // 农资弹窗
      farmStockList: [], // 农资弹窗库存
      farmStockAddList: [], // 农资添加
      addBtnShow: true,
      deleteList: [], // 删除的
      NZZLlist: [],
      landinfoList: []
    }
  },
  computed: {
    pictureList () {
      return this.$store.getters.pictureList
    },
    landDetail () {
      return this.$store.getters.landDetail
    },
    missionDetail () {
      return this.$store.getters.missionDetail
    }
  },
  destroyed () {
    this.$store.dispatch('mission/updatemissionDetail', null)
  },
  mounted () {
    this.baseId = this.$store.getters.userInfo.baseId
    this.addForm.baseId = this.$store.getters.userInfo.baseId
    this.addForm.code = this.$route.query.code
    this.addForm.name = this.$route.query.name
    if (!(this.landDetail && this.landDetail.landId)) {
      this.landDetail.landId = ''
    }
    this.getSysSonDictList('NS')
    this.addMissionData = this.$route.query
    this.$store.dispatch('user/updataRouterName', '添加农事')
    this.getLandinfoList()
    this.editForm()
    this.getUserList()
  },

  methods: {
    // 地块列表
    async getLandinfoList () {
      await getLandinfoListApi({ baseId: this.baseId }).then(res => {
        this.landinfoList = res.data
      })
    },
    // 农资搜索
    farmStockSearch () {
      clearTimeout(this.setTime)
      this.setTime = setTimeout(() => {
        this.$refs.farmStockDialog.getSearch(this.keyword, this.keywordType)
      }, 300)
    },
    addSelect (val) {
      this.$set(this.addForm, 'code', val)
    },
    del (index) {
      this.addForm.agriList.splice(index, 1)
    },
    // 字典接口
    async getSysSonDictList (code) {
      const res = await getSysSonDictListApi(code)
      this.options = res.data
      // console.log(this.landDetail, '地块详情')
      // 农资库存
      const res2 = await getFarmsStockInventoryApi({ ...this.params, baseId: this.baseId })
      this.farmStockList = res2.data.records
      this.total = res2.data.total
      const res3 = await getSysSonDictListApi('NZZL')
      this.NZZLlist = res3.data
    },
    // 用户list
    async getUserList () {
      const res = await getUserListApi(this.baseId)
      // console.log(res)
      this.userList = res.data
    },
    // 选择农资关闭弹窗子传父事件
    addFarmStock (data) {
      this.dialogVisible = false
      this.addBtnShow = false
      // console.log(data)
      const farmsStock = {}
      farmsStock.agriId = data.agriDicId
      farmsStock.type = data.type
      farmsStock.name = data.name
      farmsStock.manufacturer = data.manufacturer
      farmsStock.typeFormat = data.typeFormat
      farmsStock.specifications = data.specifications
      farmsStock.remainingQuantity = data.remainingQuantity
      this.farmStockAddList.push(farmsStock)
      // 内存指向一出 容易出现问题
      this.addForm.agriList = this.farmStockAddList
    },
    // 返回
    back () {
      this.$router.go(-1)
    },
    // 农资按钮显示
    NsCode (code) {
      switch (code) {
        case 'NS_SF':
          return true
        case 'NS_FZ':
          return true
      }
    },
    // 提交表单
    submitForm (formName) {
      if (this.addForm.agriList && !this.addForm.agriList.length && this.NsCode(this.addForm.code)) {
        this.$message.error('请添加农资信息')
        return
      }
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.addForm.baseId = this.landDetail.baseId
          this.addForm.landId = this.landDetail.landId
          let res = null
          if (this.missionDetail && this.missionDetail.id) {
            res = await updateArgiMissionApi(this.addForm)
          } else {
            res = await addArgiMissionApi(this.addForm)
          }
          if (res.code === 200) {
            this.$message.success('提交成功')
            this.$refs.upload.removeOss()
          }
          this.addForm = {}
          this.$router.go(-1) // 返回详情
        }
      })
    },
    // 农资弹窗关闭
    handleClose () {
      this.dialogVisible = false
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.$refs.upload.clearFiles()
      if (this.pictureList.length > 0) {
        for (let i = 0; i < this.pictureList.length; i++) {
          delpictureApi(this.pictureList[i])
        }
        this.$store.dispatch('mission/removePictureList')
      }
    },
    // 编辑
    editForm () {
      // console.log(this.addForm)
      if (this.missionDetail && this.missionDetail.id) {
        this.addForm = {
          ...this.missionDetail,
          participantsId: this.missionDetail.participantsId ? Number(this.missionDetail.participantsId) : null,
          name: this.$route.query.name,
          code: this.$route.query.code
        }
        this.$nextTick(() => {
          this.$store.dispatch('user/updataRouterName', '编辑农事')
        })
        // this.addForm.code = this.missionDetail.code
        // this.addForm.participants = this.missionDetail.participants
        // this.addForm.participantsId = Number(this.missionDetail.participantsId)
        // // this.addForm.area = this.missionDetail.area
        // this.addForm.time = this.missionDetail.time
        // this.addForm.way = this.missionDetail.way
        if (this.missionDetail.picture !== '') {
          this.addForm.picture = this.missionDetail.picture
        }
        // this.addForm.remark = this.missionDetail.remark
      }
    }
  }
}
</script>
<style scoped lang="scss">
.searchFlex {
  display: flex;
  align-items: center;
  .searchType {
    font-size: 20px;
    font-weight: bold;
    margin-right: 20px;
  }
  .searchInp {
    ::v-deep .el-input__inner {
      background: rgba(196, 196, 196, 0.15);
      border: none
    }
  }
  .el-icon-close {
    font-size: 24px;
    margin-left: 25px;
    color: #666666
  }
}
.addMission {
  background: #ffffff;
  position: relative;
  overflow-y: auto;
  .errorForm {
    ::v-deep .el-input__inner {
      width: 280px !important;
    }
  }
}
.back {
  position: absolute;
  top: 5%;
  left: 5%;
}

.farmStockListBox {
  .farmStockList {
    width: 450px;
    background: #edf1f4;
    border-radius: 4px;
    padding: 18px 20px;
    // display: flex;
    margin-bottom: 0.5208vw;
    position: relative;
    .icon {
      width: 0.4rem;
      height: 0.4rem;
      margin-right: 1.0417vw;
      padding: 0.5208vw;
      align-items: center;
    }
    .content {
      white-space: nowrap;
      .farmStockName {
        // margin-bottom: 0.4167vw * 0.834;
        display: flex;
        font-size: 14px;
        font-weight: bold;
        align-items: center;
        line-height: 1;
        .landType {
          margin-left: 5px;
          padding: 3px 6px 4px 6px;
          height: unset;
          background: unset;
          border: 1px solid #00C586;
          border-radius: 2px;
          text-align: center;
          color: #00C586;
          font-size: 12px;
        }
      }
      .manufacturer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        color: #999999;
        line-height: 1;
        margin-top: 15px;
      }
    }
    .num {
      // padding: 0 0.2604vw;
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #E1E1E1;
      // width: 7.2917vw;
      // height: 2.0833vw * 0.834;
      // background: #ffffff;
      // border-radius: 8px 8px 8px 8px;
      // border: 1px solid #dcdedf;
      // position: relative;
      ::v-deep .el-form-item__error {
        margin-left: 215px;
      }
      ::v-deep .el-input__inner {
        width: 160px !important;
        background-color: unset;
      }
      ::v-deep .el-form-item__content {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      ::v-deep .el-form-item {
        margin-bottom: 0
      }
      .el-input {
        width: 165px;
      }
      .el-form-item__content{
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
      .unit {
        position: absolute;
        right: 10%;
        height: 1.8vw * 0.834;
        font-size: 0.7292vw;
        top: -50%;
        color: #333;
      }
    }
    .del {
      width: 20px;
      height: 20px;
      position: absolute;
      right: -8px;
      top: -15px;
      i {
        font-size: 20px;
        color: #F76560;
      }
    }
  }
}

.addFramStockBtn {
  width: 10.4167vw;
  height: 3.1667vw * 0.834;
  border-radius: 12px 12px 12px 12px;
  background: #e8f7ef;
  color: #19b560;
  font-weight: 600;
  font-size: 0.9375vw;
  margin-bottom: 0.5208vw * 0.834;
}
.checkBox {
  background: #19B560;
  border: 1px solid #19B560;
  color: #fff
}
.checkLand {
  color: #19B560;
  border: 1px solid #19B560;
}
.agriListAdd {
  display: flex;
  align-items: flex-start;
  line-height: 1;
  span {
    margin-top: 5px;
    margin-left: 18px;
    color: #F76560
  }
}
.dialogSearch {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.demo-ruleForm {
  margin-bottom: 80px;
}
</style>
